﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.IO;

namespace SPGhostFilesManager
{
    public partial class SPGhostFilesManagerForm : Form
    {
        public SPGhostFilesManagerForm()
        {
            InitializeComponent();
            _filesGridView.AutoGenerateColumns = false;
        }

        private void _webApplications_SelectedIndexChanged(object sender, EventArgs e)
        {
            SPWebApplication application = _webApplications.SelectedItem as SPWebApplication;
            _siteCollections.Items.Clear();
            foreach (SPSite site in application.Sites)
            {
                _siteCollections.Items.Add(site);
            }
            if (_siteCollections.Items.Count > 0)
                _siteCollections.SelectedIndex = 0;
        }

        private void _siteCollections_SelectedIndexChanged(object sender, EventArgs e)
        {
            SPSite site = _siteCollections.SelectedItem as SPSite;
            _rootList.Items.Clear();
            foreach (var list in site.RootWeb.Lists)
                _rootList.Items.Add(list);
            if (_rootList.Items.Count > 0)
                _rootList.SelectedIndex = 0;
        }

        private void _rootList_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindFilesGridView();
        }

        private void BindFilesGridView()
        {
            SPList list = _rootList.SelectedItem as SPList;
            _filesGridView.DataSource = null;
            List<SPListFileItem> items = new List<SPListFileItem>();
            foreach (SPListItem item in list.Items)
            {
                if (item.File != null && item.File.CustomizedPageStatus != SPCustomizedPageStatus.Uncustomized)
                    items.Add(new SPListFileItem(item));
            }
            _filesGridView.DataSource = new SortableBindingList<SPListFileItem>(items);
        }

        private void _saveAllUnGhosted_Click(object sender, EventArgs e)
        {
            string directory = GetSaveDirectory();
            foreach (var item in ((SPListFileItem[])_filesGridView.DataSource))
                if (item.Status != SPCustomizedPageStatus.Uncustomized)
                    item.Save(directory);
        }

        private string GetSaveDirectory()
        {
            string path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), ((SPWebApplication)_webApplications.SelectedItem).DisplayName);
            path = Path.Combine(path, ((SPSite)_siteCollections.SelectedItem).RootWeb.Title);
            return Path.Combine(path, ((SPList)_rootList.SelectedItem).Title);
        }

        private void SaveItem(SPListFileItem item)
        {
            MessageBox.Show(string.Format("Item saved to: {0}", item.Save(GetSaveDirectory())));
        }

        private void _save_Click(object sender, EventArgs e)
        {
            SPListFileItem item = SelectedItem;
            SaveItem(item);
        }

        private void _revert_Click(object sender, EventArgs e)
        {
            SPListFileItem item = SelectedItem;
            if (MessageBox.Show(this, "Are you sure you want to revert this file back to its site/ feature definition version?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                SaveItem(item);
                item.Revert();
                BindFilesGridView();
            }
        }

        private void _ghost_Click(object sender, EventArgs e)
        {
            SPListFileItem item = SelectedItem;
            SPGhostListFileDialog ghostListFileDialog = new SPGhostListFileDialog();
            SPList list = _rootList.SelectedItem as SPList;
            if (DialogResult.OK == ghostListFileDialog.ShowDialog(this, list, item))
                BindFilesGridView();
        }

        private SPListFileItem SelectedItem
        {
            get
            {
                if (_filesGridView.SelectedRows.Count > 0)
                    return _filesGridView.SelectedRows[0].DataBoundItem as SPListFileItem;
                return null;
            }
        }

        private void _filesGridView_SelectionChanged(object sender, EventArgs e)
        {
            SPListFileItem item = SelectedItem;
            _save.Enabled = null != item;
            _revert.Enabled = null != item && item.Status == SPCustomizedPageStatus.Customized;
            _ghost.Enabled = null != item;
        }

        private void _refresh_Click(object sender, EventArgs e)
        {
            BindFilesGridView();
        }

        private void SPGhostFilesManagerForm_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                try
                {
                    SPServiceCollection services = SPFarm.Local.Services;
                    foreach (SPService curService in services)
                    {
                        if (curService is SPWebService)
                        {
                            SPWebService webService = (SPWebService)curService;

                            foreach (SPWebApplication webApp in webService.WebApplications)
                            {

                                if (webApp is SPAdministrationWebApplication)
                                    continue;
                                this._webApplications.Items.Add(webApp);
                            }
                        }
                    }
                    if (_webApplications.Items.Count > 0)
                        _webApplications.SelectedIndex = 0;
                }
                catch
                {
                    MessageBox.Show("SPGhostFilesManager cannot access your local SharePoint farm, Please make sure you have the approperiate permissions on the local farm.");
                    this.Close();
                }
            }
        }
    }
}
